package com.powerwyx.shortlink.project.service.impl;

import com.powerwyx.shortlink.project.service.UrlTitleService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 王艺锡
 * @version 1.0
 */
@Slf4j
@Service
public class UrlTitleServiceImpl implements UrlTitleService {

    /**
     * 根据url获取网站标题
     *
     * @param url
     * @return
     */
    @SneakyThrows
    @Override
    public String getTitle(String url) {
        URL targetUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        // 设置请求方法
        connection.setRequestMethod("GET");
        connection.connect();

        // 发起请求
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            Document document = Jsoup.connect(url).get();
            return document.title();
        }
        return "Error while fetching title";
    }

}
